package com.pro.grpcserver;

import com.google.common.net.HostAndPort;
import com.orbitz.consul.Consul;
import com.orbitz.consul.HealthClient;
import com.orbitz.consul.model.health.Service;
import com.orbitz.consul.model.health.ServiceHealth;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import com.promotion.ComputeGrpc;
import com.promotion.Promotion;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;


public class GrocServiceClientTwo {

	private static final Logger logger = Logger.getLogger(GrocServiceClientTwo.class.getName());

	private final ManagedChannel channel;

	private final ComputeGrpc.ComputeBlockingStub blockingStub;

	/**
	 * 构造方法获取一个可用的service服务地址
	 */
	public GrocServiceClientTwo(String ip) {
		Service currentService = getCurrentServiceByServiceName(ip);
		String grpcHost = currentService.getAddress();
		int grpcPort = currentService.getPort();
//		HostEnum hostEnum =HostEnum.getRandomEnum();
		channel = ManagedChannelBuilder.forAddress(grpcHost,grpcPort)
				.usePlaintext(true)
				.build();
		blockingStub = ComputeGrpc.newBlockingStub(channel);
	}

	public void shutdown() throws InterruptedException {
		channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
	}

	/**
	 * Say hello to server.
	 */
	public String greet(String name) {
		Long beginTime = System.currentTimeMillis();
		Promotion.PromotionRequest request = Promotion.PromotionRequest.newBuilder().setMessage(name).build();
		Promotion.PromotionResponse response = blockingStub.handle(request);
		try {
			Long endTime = System.currentTimeMillis();
			logger.log(Level.INFO, "请求引擎时间[" + (endTime - beginTime) + "ms]");
			return response.getMessage();
		} catch (Exception e) {
			logger.log(Level.WARNING, "RPC failed: {0}", e);
			return "{'status':-1,'message':"+e.getMessage()+"}";
		}
	}

	public static Service getCurrentServiceByServiceName(String ip) {
		logger.log(Level.INFO, "请求consul服务IP地址[" + ip + "]");
//		Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromString(ip + ":8500")).build();
//		HealthClient healthClient = consul.healthClient();
//		List<ServiceHealth> nodes = healthClient.getHealthyServiceInstances("promotion-service").getResponse();
		List<ServiceHealth> nodes = NodesUtils.getServiceHealth(ip);
		if (nodes.size() == 0) {
			return null;
		}
		ServiceHealth sh = nodes.get(new Random().nextInt(nodes.size()));
		logger.log(Level.INFO, "调用的引擎服务[" + sh.getService().getAddress() +  ":"+sh.getService().getPort()+"]");
		return sh.getService();
	}
}


